<?php
namespace App\Repos;

use App\Models\Consult;
use App\Models\WxuserInfo;
use App\Services\Wechat;
use Log;

class ConsultRepo 
{
    public static function pages($where=[],$num=5)
    {
        $query = Consult::query();
        if(array_get($where,'openid')) {
            $openid = array_pull($where,'openid');
            $query->where(function($query) use ($openid){
                $query->where('wxuser_openid','like',$openid)->orWhere('expert_openid','like',$openid);    
            });
            
        }
        if(array_get($where,'keyword')) {
            $keyword = array_pull($where,'keyword');
            $query->where('title','like','%'.$keyword.'%');
        }
    	return $query->paginate($num);
    }

    public static function find($where)
    {
    	return Consult::where($where)->first();
    }

    public static function store($data)
    {
    	$wxuserinfo = array_only($data,['truename','mobile','zhiwei','danwei']);
        $wxuserinfo['openid'] = $data['wxuser_openid'];
        WxuserInfo::updateOrCreate(['openid'=>$data['wxuser_openid']],$wxuserinfo);

        $data = array_except($data,['truename','mobile','zhiwei','danwei']);
        $flag = Consult::create($data);
        if($flag) {
            $wxuser = Wechat::getUserInfo($data['wxuser_openid']);
            $msg = $flag->toArray(); 
            $msg['first'] = '您有一条新的咨询消息，请尽快处理';        
            $msg['openid']     = $data['expert_openid'];   
            $msg['name']   = $wxuser['nickname'];
            $msg['url']    = config('app.url').'/user/consult-show/'.$flag->id;
            // 推送给专家
            Wechat::sendMsgTpl('new',$msg);
            Log::info('新单：推送给专家成功');

            //给用户回执
            $msg2 = $msg;     
            $msg2['first']  = '您已成功提交信息，请耐心等待';
            $msg2['openid'] = $data['wxuser_openid'];               
            Wechat::sendMsgTpl('new',$msg2);
            Log::info('新单：推送给用户');  
        }
        return $flag;
    }
}
